#include "sendfile.h"
#include "ui_sendfile.h"
#include "widget.h"

#include <QFileDialog>
SendFile::SendFile(QTcpSocket *s, QString whoSend, QString whoGet, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SendFile)
{
    ui->setupUi(this);
    _socket = s;
    _whoSend = whoSend;
    _whoGet = whoGet;

}

SendFile::~SendFile()
{
    delete ui;
}

void SendFile::on_btn_choseFile_clicked()
{
    // 创建文件选择对话框
    QString filePath = QFileDialog::getOpenFileName(nullptr, "选择文件", "", "所有文件 (*.*)");

    if (!filePath.isNull()) {
       qDebug() << "选择的文件路径：" << filePath;
       ui->lineEdit->setText(filePath);
       // 在这里处理选择的文件路径
    } else {
       qDebug() << "取消选择文件";
    }
}

void SendFile::on_btn_send_clicked()
{
    QDataStream stream(_socket);
    QString action = "SEND_FILE_FRIEND";
    stream << action << _whoSend << _whoGet;
//    stream << _whoSend << _whoGet;
    // 将路径的文件变成二进制数组
    QString imgPath = ui->lineEdit->text();
    QFileInfo fileInfo(imgPath);
    QString fileName = fileInfo.fileName();  // 提取文件名，结果为 "img.png"
    stream << fileName;

//    QFile file(imgPath);
//    if (file.open(QIODevice::ReadOnly)) {
//        QByteArray byteArray = file.readAll();
//        file.close();
//        stream << byteArray;
//        qDebug() << "row 52 File converted to binary data. Size: " << byteArray.size();
//        QMessageBox::information(this, "成功", "文件发送成功！");
//        // 关闭窗口
//        close();
//    } else {
//        qDebug() << "Failed to open file.";
//    }
    QFile file(imgPath);
    if (file.open(QIODevice::ReadOnly)) {
        QByteArray byteArray = file.readAll();
        file.close();

        stream << static_cast<quint32>(byteArray.size());  // 发送文件数据的大小
        stream.writeRawData(byteArray.constData(), byteArray.size());  // 发送文件数据
//        stream << byteArray;
//        _socket->waitForBytesWritten();
        qDebug() << "File converted to binary data. Size: " << byteArray.size();
        QMessageBox::information(this, "成功", "文件发送成功！");
        close();
    } else {
        qDebug() << "Failed to open file.";
    }

}
